﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace QuickDev.SSO
{
    /// <summary>
    /// Utilities
    /// </summary>
    internal class Utilities
    {
        #region Session Related

        /// <summary>
        /// WriteSession
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public static void WriteSession( string key , object value )
        {
            if ( HttpContext.Current.Session[key] != null )
                HttpContext.Current.Session[key] = value;
            else
                HttpContext.Current.Session.Add( key , value );
        }

        /// <summary>
        /// GetSession
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="defaultvalue">defaultvalue</param>
        /// <returns>Session</returns>
        public static object GetSession( string key , object defaultvalue )
        {
            try
            {
                if ( HttpContext.Current.Session[key] != null )
                    return HttpContext.Current.Session[key];
                else
                    return defaultvalue;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// RemoveSession
        /// </summary>
        /// <param name="key">key</param>
        public static void RemoveSession( string key )
        {
            if ( HttpContext.Current.Session[key] != null )
            {
                HttpContext.Current.Session.Remove( key );
            }
            else
            {
                HttpContext.Current.Session[key] = null;
            }
        }

        #endregion

        #region URL Related

        /// <summary>
        /// Gets the site root.
        /// </summary>
        /// <returns></returns>
        public static string GetSiteRoot()
        {
            string port = HttpContext.Current.Request.ServerVariables[ServerVariable.SERVER_PORT];

            if ( port == null || port == Ports.HTTP || port == Ports.HTTPS )
                port = String.Empty;
            else
                port = String.Concat( ":" , port );

            string protocol = HttpContext.Current.Request.ServerVariables[ServerVariable.SERVER_PORT_SECURE];
            if ( protocol == null || protocol == "0" )
                protocol = ProtocolPrefix.HTTP;
            else
                protocol = ProtocolPrefix.HTTPS;

            string appPath = HttpContext.Current.Request.ApplicationPath;

            if ( appPath == "/" )
                appPath = String.Empty;

            string sOut = protocol + HttpContext.Current.Request.ServerVariables[ServerVariable.SERVER_NAME] + port + appPath;

            return sOut;
        }

        #endregion
    }
}
